﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SyncLib;
using System.Threading;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar.SuperGrid.Style;
using AppCommon.Controls;
using AppCommon;
using SyncLib.Client;
using SyncApplication.Business;
using SyncApplication.Dialog;
using Microsoft.Synchronization;

namespace SyncApplication.Controls
{
    public partial class ClientConfig : UserControlBase
    {
        SyncConfigDS.ClientConfigRow clientConfig = null;
        DataTable tblDirection = new DataTable();
        public ClientConfig()
        {
            InitializeComponent();
            historySyncTableAdapter.Connection.ConnectionString = CommonVariable.SqlConnectionString;
            GridMain.PrimaryGrid.Columns["Result"].RenderType = typeof(MyGridImageControl);
            GridDateTimeInputEditControl c = (GridDateTimeInputEditControl)GridMain.PrimaryGrid.Columns["SyncDate"].RenderControl;
            c.Format = DevComponents.Editors.eDateTimePickerFormat.Custom;
            c.CustomFormat = "dd/MM/yyyy HH:mm:ss";
            dtiFromDate.Value = DateTime.Now.AddDays(-7);
            dtiToDate.Value = DateTime.Now.AddDays(1);
            tblDirection.Columns.Add("Direction");
            tblDirection.Columns.Add("Name");
            tblDirection.Rows.Add("Undefine", "Chưa chọn");
            tblDirection.Rows.Add(SyncDirectionOrder.DownloadAndUpload.ToString(), "Hai chiều");
            tblDirection.Rows.Add(SyncDirectionOrder.UploadAndDownload.ToString(), "Hai chiều(2)");
            tblDirection.Rows.Add(SyncDirectionOrder.Download.ToString(), "Chỉ tải xuống");
            tblDirection.Rows.Add(SyncDirectionOrder.Upload.ToString(), "Chỉ tải lên");
            cbDirection.DisplayMember = "Name";
            cbDirection.ValueMember = "Direction";
            cbDirection.DataSource = new DataView(tblDirection);

        }
        public void DataBind()
        {
            SyncConfigDS.ScopeInfoExRow scope = CurrentNode.Tag as SyncConfigDS.ScopeInfoExRow;
            Guid clientId = (Guid)CommonVariable.Get(ClientConst.ClientID);
            SyncConfigDS.ClientConfigRow clientRow = FrmClient.Current.TreeManipulation.SyncConfig.ClientConfig.FindByClientIdScopeExId(clientId, scope.ScopeExId);
            clientConfig = clientRow;
            if (clientRow != null)
            {
                txtScopeName.Text = scope.ScopeName;
                txtBatchSize.Text = clientRow.IsBatchSizeNull() ? "0" : clientRow.BatchSize.ToString();
                txtSchemaVersion.Text = clientRow.IsSchemaVersionNull() ? "0" : clientRow.SchemaVersion.ToString();
                txtScopeVersion.Text = clientRow.IsScopeVersionNull() ? "0" : clientRow.ScopeVersion.ToString();
                txtAssemblyVersion.Text = clientRow.IsAssemblyVersionNull() ? "0" : clientRow.AssemblyVersion.ToString();
                ckDownloadFirst.Checked = clientRow.IsDownloadFirstNull() ? false : clientRow.DownloadFirst;
                ckUploadFirst.Checked = clientRow.IsUploadFirstNull() ? false : clientRow.UploadFirst;
                cbDirection.SelectedValue = clientRow.IsDirectionNull() ? "Undefine" : clientRow.Direction;
                ckEnable.Checked = clientRow.IsEnableNull() ? false : clientRow.Enable;
                historySyncTableAdapter.FillByScope(syncHistoryDS.HistorySync, scope.ScopeName, dtiFromDate.Value, dtiToDate.Value);
                cbDirection.SelectedValue = clientRow.IsDirectionNull() ? "" : clientRow.Direction;
            }
          DateTime? lastSucess=  historySyncTableAdapter.LastSyncSuccess(scope.ScopeName);
          if (lastSucess.HasValue)
              panelEx2.Text = string.Format("Lịch sử đồng bộ({0:dd/MM/yyyy HH:mm:ss})", lastSucess.Value);
          else
              panelEx2.Text = string.Format("Lịch sử đồng bộ");


        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (clientConfig != null)
            {
                clientConfig.Enable = ckEnable.Checked;
                clientConfig.BatchSize = txtBatchSize.Value;
                clientConfig.AssemblyVersion = txtAssemblyVersion.Value;
                clientConfig.SchemaVersion = txtSchemaVersion.Value;
                clientConfig.ScopeVersion = txtScopeVersion.Value;

                clientConfig.Direction = cbDirection.SelectedValue == null ? "" : cbDirection.SelectedValue.ToString();
                FrmClient.Current.TreeManipulation.AdapterClientConfigTable.Update(clientConfig);
                clientConfig.AcceptChanges();
                MessageBox.Show("Đã lưu dữ liệu thành công");
            }
        }

        private void buttonX1_Click(object sender, EventArgs e)
        {
            if (ClientSyncContext.IsRunning)
            {
                FrmNotify.Current.SyncAppNotify.ShowBalloonTip(100, "Keeper Sync", "Quá trình đồng bộ đang chạy\n Không thể thực hiện thêm", ToolTipIcon.Error);
                return;
            }
            SyncConfigDS.ScopeInfoExRow scope = CurrentNode.Tag as SyncConfigDS.ScopeInfoExRow;
            ClientSyncContext.SyncDS.TaskSyncList.Clear();
            ClientSyncContext.AddScopeToTaskList(scope.ScopeName);
            SynchronizeHandle sync = new SynchronizeHandle();
            sync.ManualSynchronize();
        }

        private void buttonX2_Click(object sender, EventArgs e)
        {
            SyncDialog.Current.Show();
        }
        public class MyGridImageControl : GridImageEditControl
        {
            public override void SetValue(object value)
            {



                if (Image != null)
                    Image.Dispose();
                int result = -1;
                if (int.TryParse(value.ToString(), out result))
                {

                    if (result == 0)
                    {
                        Image = Image.FromFile(Application.StartupPath + @"\Animation\Grid\Success.png");
                        if (this.EditorCell.Tag == null)
                        {
                            Background bg = new Background();
                            bg.Color1 = Properties.Settings.Default.SuccessColor;
                            this.EditorCell.GridRow.CellStyles.Default.Background = bg;
                        }

                    }
                    if (result == 1)
                    {
                        Image = Image.FromFile(Application.StartupPath + @"\Animation\Grid\Warning.png");
                        if (this.EditorCell.Tag == null)
                        {
                            Background bg = new Background();
                            bg.Color1 = Properties.Settings.Default.WarningColor;
                            this.EditorCell.GridRow.CellStyles.Default.Background = bg;
                        }
                    }
                    if (result == -1)
                    {
                        Image = Image.FromFile(Application.StartupPath + @"\Animation\Grid\Error.png");
                        if (this.EditorCell.Tag == null)
                        {
                            Background bg = new Background();
                            bg.Color1 = Properties.Settings.Default.ErrorColor;
                            this.EditorCell.GridRow.CellStyles.Default.Background = bg;
                        }
                    }
                    this.EditorCell.Tag = "1";

                }
                else
                {
                    this.EditorCell.Tag = null;
                    base.SetValue(value);
                }
            }
        }

        private void GridMain_Click(object sender, EventArgs e)
        {

        }

        private void panelEx2_Click(object sender, EventArgs e)
        {

        }

        private void GridMain_RowDoubleClick(object sender, GridRowDoubleClickEventArgs e)
        {
            SyncHistoryDS.HistorySyncRow row = GridMain.GetDataRow<SyncHistoryDS.HistorySyncRow>(e.GridRow.RowIndex);
            DetailSync frm = new DetailSync();
            frm.ShowMessage(row.CopeName + "[" + row.Result + "]", row.Comment, row);
            frm.Dispose();
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            DataBind();
        }

        private void btnReviewed_Click(object sender, EventArgs e)
        {
            SyncConfigDS.ScopeInfoExRow scope = CurrentNode.Tag as SyncConfigDS.ScopeInfoExRow;

            historySyncTableAdapter.UpdateReviewed(scope.ScopeName);
            FrmNotify.Current.SetDefaultIcon();
        }
    }
}
